/**
  * Copyright (c) CSIRO Australia, 2009
  *
  * @author $Author: jia020 $
  * @version $Id: QueryPanel.java 643 2009-05-20 00:20:55Z jia020 $
  */
package au.csiro.nt.pdsp.client;

import java.util.HashMap;
import java.util.Map;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.Record;
import com.gwtext.client.data.SimpleStore;
import com.gwtext.client.data.Store;

import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Panel;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Checkbox;
import com.gwtext.client.widgets.form.ComboBox;
import com.gwtext.client.widgets.form.DateField;
import com.gwtext.client.widgets.form.Field;
import com.gwtext.client.widgets.form.FieldSet;
import com.gwtext.client.widgets.form.Form;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.MultiFieldPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.VType;
import com.gwtext.client.widgets.form.event.ComboBoxListenerAdapter;
import com.gwtext.client.widgets.form.event.ComboBoxCallback;
import com.gwtext.client.widgets.layout.ColumnLayoutData;

/**
 * QueryPanel class to create query panel. 
 *
 */
public class QueryPanel extends Panel {
	private EventHandler eventHandler = null;
	private final PDQueryServiceAsync service = GWT.create(PDQueryService.class);	
	private FormPanel formPanel;
	public QueryPanel(final EventHandler eventHandler) {
		this.eventHandler = eventHandler;
		this.setBorder(false);
		this.setPaddings(15);
		// create the form
		formPanel = new FormPanel();
		formPanel.setTitle("Setup query criteria");
		formPanel.setFrame(true);
		formPanel.setPaddings(5, 5, 5, 0);
		formPanel.setWidth(350);
		formPanel.setLabelWidth(75);
		formPanel.setUrl("save-form.php");
		// create first collapsible fieldset with checkbox
		FieldSet criteriaFS = new FieldSet("Setup criterias");
		criteriaFS.setCollapsible(true);
		criteriaFS.setAutoHeight(true);
		
		TextField first = new TextField("First /Last", "first", 80);
		first.setAllowBlank(true);
		first.setName("Cfirstname");
		TextField last = new TextField("Last Name", "last", 80);
		last.setHideLabel(true);
		last.setName("Clastname");
		MultiFieldPanel namePanel = new MultiFieldPanel();
		namePanel.addToRow(first, 210);
		namePanel.addToRow(last, new ColumnLayoutData(1));		
		criteriaFS.add(namePanel);

		ComboBox cbMartial = createCBMartial();
		criteriaFS.add(cbMartial);
		
		DateField birth = new DateField("Born Before:", "birthday", 210);
		birth.setFormat("Y-m-d");
		birth.setName("Cbirthday");
		criteriaFS.add(birth);

		TextField email = new TextField("Email", "email", 210);
		email.setVtype(VType.EMAIL);
		email.setName("Cemail");
		criteriaFS.add(email);

		ComboBox cbSuburb = createCBSuburb();
		criteriaFS.add(cbSuburb);
/*
		// create another FieldSet
		FieldSet detailsFS = new FieldSet("Phone Number");
		detailsFS.setCollapsible(true);
		detailsFS.setAutoHeight(true);

		TextField home = new TextField("Home", "home", 210);
		home.setValue("(02) 9372 4696");
		detailsFS.add(home);

		TextField business = new TextField("Business", "business", 210);
		detailsFS.add(business);

		TextField mobile = new TextField("Mobile", "mobile", 210);
		detailsFS.add(mobile);

		TextField fax = new TextField("Fax", "fax", 210);
		detailsFS.add(fax);
*/
		// create Result FieldSet
		FieldSet resultFS = new FieldSet("Setup resultset");
		resultFS.setCollapsible(true);
		resultFS.setAutoHeight(true);

		Checkbox basic = new Checkbox("Basic");
		basic.setName("Rbasic");
		basic.setChecked(true);
	//	basic.disable();
		resultFS.add(basic);
		Checkbox contact = new Checkbox("Contact");
		contact.setName("Rcontact");
		contact.setChecked(true);
		resultFS.add(contact);			
		Checkbox financial = new Checkbox("Financial");
		financial.setName("Rfinancial");
		resultFS.add(financial);	
		Checkbox medical = new Checkbox("Medical");
		medical.setName("Rmedical");
		resultFS.add(medical);	
		Checkbox others = new Checkbox("Others");
		others.setName("Rothers");
		resultFS.add(others);			
		
		formPanel.add(criteriaFS);
		//formPanel.add(detailsFS);
		formPanel.add(resultFS);		
		
		Button btQuery = new Button("Query"); 
		btQuery.addListener(new ButtonListenerAdapter() {  
			public void onClick(Button button, EventObject e) { 
				Map formData = getFormDataAsMap(formPanel.getForm());
				service.queryServer(formData, new AsyncCallback<String>() {
					public void onFailure(Throwable caught) {
						// Show the RPC error message to the user
					  MessageBox.alert("failed on query");
					}

					public void onSuccess(String result) {
						//MessageBox.alert(result);	
						eventHandler.processEvent(PdspConst.EVENT_QUERY_PRIVACYDATA,result);
					}
				});				
	
			}  
			});  
		formPanel.addButton(btQuery);
		formPanel.addButton(new Button("Clear"));

		this.add(formPanel);
	}

	private ComboBox createCBSuburb() {
		// create a Store using local array data
		final Store store = new SimpleStore(
				new String[] { "suburb", "state", "postcode" }, getStates());
		store.load();

		final ComboBox cb = new ComboBox();
		cb.setForceSelection(true);
		cb.setMinChars(1);
		cb.setFieldLabel("Suburb");
		cb.setStore(store);
		cb.setDisplayField("suburb");
		cb.setMode(ComboBox.LOCAL);
		cb.setTriggerAction(ComboBox.ALL);
		cb.setEmptyText("Enter suburb");
		cb.setLoadingText("Searching...");
		cb.setTypeAhead(true);
		cb.setSelectOnFocus(true);
		cb.setWidth(210);
		cb.setHideTrigger(false);
		cb.setName("Csuburb");

		cb.addListener(new ComboBoxListenerAdapter() {
			public boolean doBeforeQuery(ComboBox comboBox, ComboBoxCallback cb) {
				System.out.println("ComboBox::doBeforeQuery()");
				return true;
			}

			public boolean doBeforeSelect(ComboBox comboBox, Record record, int index) {
				System.out.println("ComboBox::doBeforeSelect("
						+ record.getAsString("suburb") + ")");
				return super.doBeforeSelect(comboBox, record, index);
			}

			public void onCollapse(ComboBox comboBox) {
				System.out.println("ComboBox::onCollapse()");
			}

			public void onExpand(ComboBox comboBox) {
				System.out.println("ComboBox::onExpand()");
			}

			public void onSelect(ComboBox comboBox, Record record, int index) {
				System.out.println("ComboBox::onSelect('" + record.getAsString("state")
						+ "')");
			}

			public void onBlur(Field field) {
				System.out.println("ComboBox::onBlur()");
			}

			public void onChange(Field field, Object newVal, Object oldVal) {
				System.out.println("ComboBox::onChange(" + oldVal + "-->" + newVal
						+ ")");
			}

			public void onFocus(Field field) {
				System.out.println("ComboBox::onFocus()");
			}

			public void onInvalid(Field field, String msg) {
				super.onInvalid(field, msg);
			}

			public void onSpecialKey(Field field, EventObject e) {
				System.out.println("ComboBox::onSpecialKey(key code " + e.getKey()
						+ ")");
			}
		});
		return cb;
	}
	private ComboBox createCBMartial() {
		// create a Store using local array data
		final Store store = new SimpleStore(
				new String[] { "martial"}, getMartial());
		store.load();

		final ComboBox cb = new ComboBox();
		cb.setForceSelection(true);
		cb.setMinChars(1);
		cb.setFieldLabel("Martial");
		cb.setStore(store);
		cb.setDisplayField("martial");
		cb.setMode(ComboBox.LOCAL);
		cb.setTriggerAction(ComboBox.ALL);
		//cb.setEmptyText("Enter martial");
		cb.setLoadingText("Searching...");
		cb.setTypeAhead(true);
		cb.setSelectOnFocus(true);
		cb.setWidth(210);
		cb.setName("Cmartial");

		cb.setHideTrigger(false);

		cb.addListener(new ComboBoxListenerAdapter() {
			public boolean doBeforeQuery(ComboBox comboBox, ComboBoxCallback cb) {
				System.out.println("ComboBox::doBeforeQuery()");
				return true;
			}

			public boolean doBeforeSelect(ComboBox comboBox, Record record, int index) {
				System.out.println("ComboBox::doBeforeSelect("
						+ record.getAsString("suburb") + ")");
				return super.doBeforeSelect(comboBox, record, index);
			}

			public void onCollapse(ComboBox comboBox) {
				System.out.println("ComboBox::onCollapse()");
			}

			public void onExpand(ComboBox comboBox) {
				System.out.println("ComboBox::onExpand()");
			}

			public void onSelect(ComboBox comboBox, Record record, int index) {
				System.out.println("ComboBox::onSelect('" + record.getAsString("state")
						+ "')");
			}

			public void onBlur(Field field) {
				System.out.println("ComboBox::onBlur()");
			}

			public void onChange(Field field, Object newVal, Object oldVal) {
				System.out.println("ComboBox::onChange(" + oldVal + "-->" + newVal
						+ ")");
			}

			public void onFocus(Field field) {
				System.out.println("ComboBox::onFocus()");
			}

			public void onInvalid(Field field, String msg) {
				super.onInvalid(field, msg);
			}

			public void onSpecialKey(Field field, EventObject e) {
				System.out.println("ComboBox::onSpecialKey(key code " + e.getKey()
						+ ")");
			}
		});
		return cb;		
	}
	private static String[][] getMartial() {
		return new String[][] {
				new String[] { "Single" },
				new String[] { "Married" },
				new String[] { "Seperated" },
				new String[] { "Divorced"},
				new String[] { "Widowed"},
				new String[] { "De facto"} };
	}	
	private static String[][] getStates() {
		return new String[][] {
				new String[] { "Epping", "NSW", "2121" },
				new String[] { "Ryde", "NSW", "2112" },
				new String[] { "Sydney", "NSW", "2000" },
				new String[] { "Marsfield", "NSW", "2122" },
				new String[] { "Bondi", "NSW", "2026" },
				new String[] { "North shore", "NSW", "2060" },
				new String[] { "Eastwood", "NSW", "2122" },
				new String[] { "Burwood", "NSW", "2134" },};
	}
	public Map getFormDataAsMap(Form form) {
		//username=abcd&password=abcd etc...
		String formValues = form.getValues();
		Map formData = new HashMap<String,String>();
		String[] nameValuePairs = formValues.split("&");
		
		for(int i=0; i<nameValuePairs.length; ++i) {
			String[] oneItem = nameValuePairs[i].split("=");
			if (oneItem.length == 2)
				formData.put(oneItem[0],oneItem[1]);
		}
		return formData;		
	}
}

